package com.ynyr.jar.common.jpa.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.StringUtils;
import org.springframework.context.ApplicationContextException;
import org.springframework.core.env.Environment;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.function.Function;

public class DataSourceBuilder {
    private static final Logger logger = LoggerFactory.getLogger(DataSourceBuilder.class);

    public static final DruidDataSource build(final Environment environment, String prefix) throws SQLException {
        Function<String, String> getProperty = property -> environment.getProperty(prefix + "." + property);

        if (StringUtils.isEmpty(getProperty.apply("url"))) {
            logger.error("数据库连接池配置错误!"
                    + " 请检查Spring配置文件，目前的配置有："
                    + Arrays.toString(environment.getActiveProfiles()));
            throw new ApplicationContextException(
                    "数据库连接池配置错误");
        }

        final DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(getProperty.apply("driver-class-name"));
        druidDataSource.setUrl(getProperty.apply("url"));
        druidDataSource.setUsername(getProperty.apply("username"));
        druidDataSource.setPassword(getProperty.apply("password"));
        druidDataSource.setInitialSize(Integer.parseInt(getProperty.apply("initialSize")));
        druidDataSource.setMinIdle(Integer.parseInt(getProperty.apply("minIdle")));
        druidDataSource.setMaxActive(Integer.parseInt(getProperty.apply("maxActive")));
        druidDataSource.setMaxWait(Integer.parseInt(getProperty.apply("maxWait")));
        druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(getProperty.apply("timeBetweenEvictionRunsMillis")));
        druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(getProperty.apply("minEvictableIdleTimeMillis")));
        druidDataSource.setValidationQuery(getProperty.apply("validationQuery"));
        druidDataSource.setTestWhileIdle(Boolean.parseBoolean(getProperty.apply("testWhileIdle")));
        druidDataSource.setTestOnBorrow(Boolean.parseBoolean(getProperty.apply("testOnBorrow")));
        druidDataSource.setTestOnReturn(Boolean.parseBoolean(getProperty.apply("testOnReturn")));
        druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(getProperty.apply("poolPreparedStatements")));
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(getProperty.apply("maxPoolPreparedStatementPerConnectionSize")));
        druidDataSource.setFilters("stat");

        return druidDataSource;
    }
}